/**
 * fileName:com.zimo.web.ctl.User.java
 * projectName:Zimo
 */
package com.zimo.web.ctl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.model.BucketSummary;
import com.zimo.web.entity.User;
import com.zimo.web.service.UserService;
import com.zimo.web.util.CloudUtil;
import com.zimo.web.util.ContentTypeUtil;
import com.zimo.web.util.MD5;
import com.zimo.web.util.PropertyUtil;

/**
 * 用户控制类
 * 
 * @author sg.z/2013-12-16/下午5:43:46
 */
@Controller
@RequestMapping(value = "user")
public class UserCtl extends SuperCtl {

	private Logger log = Logger.getLogger(UserCtl.class);

	@Resource
	private UserService userService;

	/**
	 * 用户登录
	 * 
	 * @author sg/2013-12-16/下午5:44:59
	 */
	@RequestMapping(value = "/register.htm", method = RequestMethod.POST)
	public String register(HttpServletRequest request, HttpServletResponse response, @Valid User user,
			BindingResult result) {

		String status = "success";
		String msg = "";
		// 验证传入的对象user字段
		if (result.hasErrors()) {
			List<FieldError> list = result.getFieldErrors();
			for (FieldError fieldError : list) {
				String field = fieldError.getField();
				String error = fieldError.getDefaultMessage();
				log.debug("# register() 注册异常:field:" + field + " error:" + error);
				msg += error + ";";
			}
			status = "fail";
		}
		// 验证两次密码是否一致
		String rePass = StringUtils.trim(user.getRePass());
		String pass = StringUtils.trim(user.getUserPass());
		if (!StringUtils.equalsIgnoreCase(rePass, pass)) {
			log.debug("# register() 注册异常:两次输入密码不一致");
			status = "fail";
			msg += "两次输入密码不一致;";
		}

		if (StringUtils.equals(status, "success")) {
			msg = "注册成功，请登录!";
		} else {// 错误直接返回,不用再执行下面的保存操作了
			super.ajaxResponse(response, null, status,msg);
			return null;
		}
		pass = MD5.md5(pass);
		user.setUserPass(pass);

		// 检查用户是否存在
		User user1 = userService.getUserByName(user.getUserName());
		User user2 = userService.getUserByEmail(user.getUserEmail());
		if (user1 != null) {
			status = "fail";
			msg = "用户已存在,请重新填写用户名";
			super.ajaxResponse(response, null, status,msg);
			return null;
		}
		if (user2 != null) {
			status = "fail";
			msg = "邮箱已存在,请重新填写用户邮箱";
			super.ajaxResponse(response, null, status,msg);
			return null;
		}

		// 上传头像
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		MultipartFile mfile = multiRequest.getFile("file");
		if (mfile != null) {
			// 获取云存储需要的参数
			String host = PropertyUtil.getStrValue("cloud.properties", "host", "bcs.duapp.com");
			String accessKey = PropertyUtil.getStrValue("cloud.properties", "accessKey", "UNAZIoifqmHcDa7yaRVPT6bd");
			String secretKey = PropertyUtil.getStrValue("cloud.properties", "secretKey",
					"o6eBB9dasZ8KlgDhanPKN7ARSmXd0kYT");
			BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
			BaiduBCS baiduBCS = new BaiduBCS(credentials, host);
			baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8

			List<BucketSummary> bucketList = CloudUtil.listBucket(baiduBCS);
			String bucket = PropertyUtil.getStrValue("cloud.properties", "bucket", "zimo-home");
			if (bucketList == null) {
				CloudUtil.createBucket(baiduBCS, bucket);
			} else {
				boolean boo = false;
				for (BucketSummary bucketSummary : bucketList) {
					// 有该bucket，跳出
					if (StringUtils.equalsIgnoreCase(bucket, bucketSummary.getBucket())) {
						boo = true;
						break;
					}
				}
				// 没有该bucket，创建一个
				if (!boo) {
					CloudUtil.createBucket(baiduBCS, bucket);
				}
			}
			String contentType = mfile.getContentType();
			boolean boo = ContentTypeUtil.contains("img", contentType);
			if (!boo) {
				status = "fail";
				msg = "头像请上传图片类型文件";
				super.ajaxResponse(response, null, status,msg);
				return null;
			}
			String fileName = mfile.getOriginalFilename().trim();
			String ext = fileName.substring(fileName.indexOf("."), fileName.length());
			String object = "/image/" + System.currentTimeMillis() + ext;

			try {
				InputStream fileContent = mfile.getInputStream();
				// 上传到云存储
				CloudUtil.putObjectByInputStream(baiduBCS, fileContent, bucket, object, contentType, mfile.getSize());
			} catch (IOException e) {
				e.printStackTrace();
				status = "fail";
				msg = "系统异常,请稍后再试";
				super.ajaxResponse(response, null, status,msg);
				return null;
			}
			String headUrl = CloudUtil.generateUrl(baiduBCS, bucket, object, null, 0l, 0l);
			user.setHeadUrl(headUrl);
		}
		userService.insertUser(user);
		super.ajaxResponse(response, null, status,msg);
		return null;
	}

}
